package com.example.demo.jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.*;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-08-22 10:03 AM
 */
@WebServlet(name="select blob test", urlPatterns = {"/blob/select"})
public class SelectBlobTest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Connection conn = null;
        String id = req.getParameter("id");
        if(id == null || "".equals(id)) {
            resp.getWriter().println("Id is required.");
            return;
        }
        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection("jdbc:h2:C:/study/db/h2/bin/test;AUTO_SERVER=TRUE;AUTO_RECONNECT=TRUE", "sa", "123");
            Statement stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery("select * from test where id= " + id);
            //resp.getWriter().println("id, name, birthday, my blob");
            byte content[] = new byte[8092];
            while(rs.next()) {
                Blob blob = rs.getBlob("my_blob");
                InputStream is = blob.getBinaryStream();
                OutputStream os = resp.getOutputStream();
                int count = 0;
                while((count = is.read(content)) != -1) {
                    os.write(content, 0, count);
                }
            }


        } catch (ClassNotFoundException | SQLException e) {
            return;
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }


    }
}
